package com.ebupt.migu.music.redis.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.DataType;
import org.springframework.data.redis.core.*;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author Administrator
 * @date 2017/12/1
 */
@Service
@Slf4j
public class RedisService {

    private RedisTemplate redisTemplate;

    @Autowired(required = false)
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        RedisSerializer stringSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringSerializer);
        redisTemplate.setValueSerializer(stringSerializer);
        redisTemplate.setHashKeySerializer(stringSerializer);
        redisTemplate.setHashValueSerializer(stringSerializer);
        this.redisTemplate = redisTemplate;
    }

    /**
     * 写入缓存
     *
     * @param key
     * @param value
     * @return
     */
    public boolean set(final String key, Object value) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 写入缓存
     *
     * @param key
     * @param value
     * @return
     */
    public boolean setSet(final String key, Set value) {
        boolean result = false;
        try {
            SetOperations<Serializable, Object> operations = redisTemplate.opsForSet();
            for (Object obj : value) {
                operations.add(key, obj);
            }
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 写入缓存设置时效时间
     *
     * @param key
     * @param value
     * @return
     */
    public boolean set(final String key, Object value, Long expireTime) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 批量删除对应的value
     *
     * @param keys
     */
    public void remove(final String... keys) {
        for (String key : keys) {
            remove(key);
        }
    }

    /**
     * 批量删除key
     *
     * @param pattern
     */
    public void removePattern(final String pattern) {
        Set<Serializable> keys = redisTemplate.keys(pattern);
        if (keys.size() > 0)
            redisTemplate.delete(keys);
    }

    /**
     * 删除对应的value
     *
     * @param key
     */
    public void remove(final String key) {
        if (exists(key)) {
            redisTemplate.delete(key);
            redisTemplate.opsForSet().remove(key);
        }
    }

    /**
     * 删除对应的value
     *
     * @param key
     */
    public void remove_key(final String key) {
        if (exists(key)) {
            redisTemplate.unlink(key);
        }
    }

    /**
     * 判断缓存中是否有对应的value
     *
     * @param key
     * @return
     */
    public boolean exists(final String key) {
        return redisTemplate.hasKey(key);
    }

    /**
     * 读取缓存
     *
     * @param key
     * @return
     */
    public Object get(final String key) {
        Object result = null;
        ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
        result = operations.get(key);
        return result;
    }

    /**
     * 读取缓存
     *
     * @param key
     * @return
     */
    public Set<Object> getSet(final String key) {
        try {
            Set<Object> resultSet = redisTemplate.opsForSet().members(key);
            return resultSet;
        }catch (Exception e){
            try {
                Thread.sleep(60000);
            }catch (Exception e2){
                e2.printStackTrace();
            }
            e.printStackTrace();
            System.out.println("getredis获取数据异常");
            Set<Object> set = getSet(key);
            return set;
        }
    }

    /**
     * 哈希 添加
     *
     * @param key
     * @param hashKey
     * @param value
     */
    public void hmSet(String key, Object hashKey, Object value) {
        HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
        hash.put(key, hashKey, value);
    }

    /**
     * 哈希获取数据
     *
     * @param key
     * @param hashKey
     * @return
     */
    public Object hmGet(String key, Object hashKey) {
        HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
        return hash.get(key, hashKey);
    }

    /**
     * 列表添加
     *
     * @param k
     * @param v
     */
    public void lPush(String k, Object v) {
        ListOperations<String, Object> list = redisTemplate.opsForList();
        list.rightPush(k, v);
    }

    /**
     * 列表获取
     *
     * @param k
     * @param l
     * @param l1
     * @return
     */
    public List<Object> lRange(String k, long l, long l1) {
        ListOperations<String, Object> list = redisTemplate.opsForList();
        return list.range(k, l, l1);
    }

    /**
     * 集合添加
     *
     * @param key
     * @param value
     */
    public void add(String key, Object value) {
        SetOperations<String, Object> set = redisTemplate.opsForSet();
        set.add(key, value);
    }

    /**
     * 集合获取
     *
     * @param key
     * @return
     */
    public Set<Object> setMembers(String key) {
        SetOperations<String, Object> set = redisTemplate.opsForSet();
        return set.members(key);
    }

    /**
     * 有序集合添加
     *
     * @param key
     * @param value
     * @param scoure
     */
    public void zAdd(String key, Object value, double scoure) {
        ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
        zset.add(key, value, scoure);
    }

    /**
     * 有序集合获取
     *
     * @param key
     * @param scoure
     * @param scoure1
     * @return
     */
    public Set<Object> rangeByScore(String key, double scoure, double scoure1) {
        ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
        return zset.rangeByScore(key, scoure, scoure1);
    }

    /**
     * 交集
     *
     * @param sourceSet1
     * @param sourceSet2
     * @param targetSet
     * @return
     */
    public void intersectAndStore(String sourceSet1, String sourceSet2, String targetSet) {
        redisTemplate.opsForSet().intersectAndStore(sourceSet1, sourceSet2, targetSet);
    }

    /**
     * 交集
     *
     * @param sourceSet1
     * @param sourceSet2
     * @return
     */
    public Set intersect(String sourceSet1, String sourceSet2) {
        return redisTemplate.opsForSet().intersect(sourceSet1, sourceSet2);
    }

    /**
     * 并集
     *
     * @param sourceSet1
     * @param sourceSet2
     * @param targetSet
     * @return
     */
    public void unionAndStore(String sourceSet1, String sourceSet2, String targetSet) {
        redisTemplate.opsForSet().unionAndStore(sourceSet1, sourceSet2, targetSet);
    }

    /**
     * 并集
     *
     * @param sourceSet1
     * @param sourceSet2
     * @return
     */
    public Set union(String sourceSet1, String sourceSet2) {
        return redisTemplate.opsForSet().union(sourceSet1, sourceSet2);
    }

    /**
     * 差集
     *
     * @param sourceSet1
     * @param sourceSet2
     * @param targetSet
     * @return
     */
    public void differenceAndStore(String sourceSet1, String sourceSet2, String targetSet) {
        redisTemplate.opsForSet().differenceAndStore(sourceSet1, sourceSet2, targetSet);
    }

    /**
     * 差集
     *
     * @param sourceSet1
     * @param sourceSet2
     * @return
     */
    public Set difference(String sourceSet1, String sourceSet2, String targetSet) {
        return redisTemplate.opsForSet().difference(sourceSet1, sourceSet2);
    }

    /**
     * 类型
     *
     * @param type
     * @return
     */
    public DataType type(String type) {
        return redisTemplate.type("type");
    }

    /**
     * 批量删除key值
     *
     * @param keys redis中key
     */
    public void unlink(final String... keys) {
        for (String key : keys) {
            if (exists(key)) {
                redisTemplate.unlink(key);
            }
        }
    }


    /**
     * 重复建立redis中key的连接
     *
     * @param key key
     * @param i 计数器
     * @return 连接结果
     */
    public BoundSetOperations<String, String> unlinkAndGetConnect(String key, int i) {
        try {
            unlink(key);
            BoundSetOperations<String, String> boundSetOperations = redisTemplate.boundSetOps(key);
            return boundSetOperations;
        } catch (Exception e) {
            try {
                Thread.sleep(5000L);
            } catch (InterruptedException ex) {
                log.info("主线程睡眠异常" + ex.getMessage());
            }
            i++;
            log.info("递归次数：" + i + "，key：" + key + "连接redis异常：" + e.getMessage());
            return unlinkAndGetConnect(key, i);
        }
    }
}